import os
import ahocorasick
import json

'''
Level 2推理引擎
L1 内容传入: '红点石斑鱼简介'
{'args': {'红点石斑鱼': ['fish_name']}, 'questions_types': ['某鱼简介']}
L2 做进一步推理, 细化内容, 并封装cypher查询语句
'''


class L2_engine:

    def build_entity_dict(self, keywords):
        """
        构建节点实体(查询实体)
        :param keywords:
        :return:
        """
        entity_dict = {}
        for wds, types in keywords.items():
            for type in types:
                if type not in entity_dict:
                    entity_dict[type] = [wds]
                else:
                    entity_dict[type].append(wds)
        return entity_dict

    def L2_inference(self, L1_inf):
        """
        L2推理引擎, 本类主入口
        :param L1_inf:
        :return:
        """
        # 取出关键字实体
        keywords = L1_inf['args']
        entity_dict = self.build_entity_dict(keywords)
        # 取出查询类型
        questions_types = L1_inf['questions_types']

        # 封装cypher查询语句
        my_cypher = []
        # 推理过程 --> 匹配规则
        # rules
        with open('../Knowledge_base/L2_Knowledge_base/rules/L2_rules.json', 'r', encoding='utf-8') as f:
            json_file_str = f.read()
            # loads要求字符串
            rules_dict = json.loads(json_file_str)
        for question_type in questions_types:
            cypher_ = {}
            cypher_['question_type'] = question_type
            tmp_cypher = []
            for k, v in rules_dict.items():
                if question_type == k:
                    tmp_cypher = [v[1].format(i) for i in entity_dict.get(v[0])]
            if tmp_cypher:
                cypher_['cypher'] = tmp_cypher
                my_cypher.append(cypher_)
        return my_cypher

    # def cypher_encapsulation(question_type, entity):
    #     sql = []


if __name__ == '__main__':
   L2_inf = L2_engine()